package com.stage.proxy;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * Created by Stage on 2017/3/7.
 */
class FileOperation {
    /**
     * 传入文件名和内容写入文件
     *
     * @param file
     * @param conent
     */
    public void fileWriter(String file, String conent) {
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file, true)));
            out.write(conent + "\r\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 存储person对象的字段
     *
     * @param className
     * @return
     */
    public boolean saveFieldFromPerson(String className) {
        try {
            Class<?> tempClass = Class.forName(className);
            Constructor constructor = tempClass.getConstructor();
            Object person = constructor.newInstance();
            saveFiled(tempClass, person, "idNo", "165464646546");
            saveFiled(tempClass, person, "name", "张小平");
            saveFiled(tempClass, person, "gender", "male");
            saveFiled(tempClass, person, "isMerried", true);
            saveFiled(tempClass, person, "age", new Integer(23));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private void saveFiled(Class<?> tempClass, Object object, String filedName, String value) {
        try {
            Field filed = tempClass.getDeclaredField(filedName);
            filed.setAccessible(true);
            filed.set(object, value);
            fileWriter("Filed.txt", filedName + "=" + filed.get(object).toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveFiled(Class<?> tempClass, Object object, String filedName, boolean value) {
        try {
            Field filed = tempClass.getDeclaredField(filedName);
            filed.setAccessible(true);
            filed.set(object, value);
            fileWriter("Filed.txt", filedName + "=" + filed.get(object).toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveFiled(Class<?> tempClass, Object object, String filedName, Integer value) {
        try {
            Field filed = tempClass.getDeclaredField(filedName);
            filed.setAccessible(true);
            filed.set(object, value);
            fileWriter("Filed.txt", filedName + "=" + filed.get(object).toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
